package com.penghaonan.appframework.utils.recyclerview;

import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerViewAdapter {
    public abstract static class OnItemViewActionListener implements RecyclerView.OnItemTouchListener {

        private GestureDetectorCompat gestureDetector;
        private RecyclerView recyclerView;

        @Override
        public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
            if (recyclerView == null) {
                recyclerView = rv;
            }
            return false;
        }

        @Override
        public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
            if (recyclerView == null) {
                recyclerView = rv;
            }
            initGestureDetector();
            gestureDetector.onTouchEvent(e);
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }

        protected abstract <T extends RecyclerView.ViewHolder> void onItemClick(T view);

        private void initGestureDetector() {
            if (gestureDetector == null) {
                if (recyclerView != null) {
                    gestureDetector = new GestureDetectorCompat(recyclerView.getContext(), new GestureDetector.OnGestureListener() {
                        @Override
                        public boolean onDown(MotionEvent e) {
                            return false;
                        }

                        @Override
                        public void onShowPress(MotionEvent e) {

                        }

                        @Override
                        public boolean onSingleTapUp(MotionEvent e) {
                            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                            if (child != null) {
                                RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
                                onItemClick(vh);
                            }
                            return true;
                        }

                        @Override
                        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                            return false;
                        }

                        @Override
                        public void onLongPress(MotionEvent e) {

                        }

                        @Override
                        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                            return false;
                        }
                    });
                }
            }
        }
    }
}
